
#include <pic18.h>  
#include "my_macros.h"
#include "hardware.h" 
#include "RF_TX.h"


#define 	CLOCK           			40			// MHz
#define 	TE            				150     	// us
#define 	OVERSAMPLING    			3       
#define 	PERIOD          			TE/OVERSAMPLING*CLOCK/4
#define	MIPS							CLOCK*1000L/4 				/* operations per 1 ms */

#define  PILOT				4500L //us

#define  TIME_PILOT		(PILOT*OVERSAMPLING/TE)

#define  ONE__HIGH_LEVEL	3
#define  ONE__LOW_LEVEL		9

#define  ZERO__HIGH_LEVEL	9
#define  ZERO__LOW_LEVEL	3


unsigned char RF_Tx_Buffer[RF_TX_BUFFER_SIZE];

near bit RF_TX_END_OF_TRANSMIT;
volatile near bit RF_TX_START;

enum
{
	RESET,
	TRANSMIT_PILOT,
	TRANSMIT_ONE__START,
	TRANSMIT_ZERO__START,
	END_OF_BIT_TRANSMIT,
	HIGH_LEVEL,
	LOW_LEVEL,
	SYNCHRO_BIT,
	NEXT_BIT

};

void Init_RF_Transmitter ( void )
{
	PIN_RF_TX_ENABLE = FALSE;
	PIN_RF_TX_ENABLE_DIR = OUTPUT;

	PIN_RF_TX = 0;
	PIN_RF_TX_DIR = OUTPUT;

	RF_TX_END_OF_TRANSMIT = FALSE;
	RF_TX_START = FALSE;
}

 
void RF_Transmitter( void )
{
	static unsigned char State = RESET, Count, pRF_Tx_Buffer, SelectBit;

    TMR3 = -PERIOD;             // reload
    TMR3IF = 0;
	
	switch ( State )
	{
		case RESET:
			Count = TIME_PILOT+1;
			State = TRANSMIT_PILOT;
			pRF_Tx_Buffer = 0;
			PIN_RF_TX = 0;		  
			SelectBit = 1;
			break;

		case NEXT_BIT:
		
			if ( RF_Tx_Buffer[pRF_Tx_Buffer] & SelectBit )
			{
				State = TRANSMIT_ONE__START;
				Count = ONE__HIGH_LEVEL-1;
			}
			else
			{
				State = TRANSMIT_ZERO__START;
				Count = ZERO__HIGH_LEVEL-1;
			}
			
			//SelectBit <<= 1;

			if ( SelectBit == 0 )
			{
				SelectBit++;
				if ( ++pRF_Tx_Buffer == RF_TX_BUFFER_SIZE)
				{
					Count = ONE__HIGH_LEVEL-1;
					State = SYNCHRO_BIT;
				}
			}

			break;	

		case TRANSMIT_PILOT:
			if ( --Count == 0 )
			{
				State = NEXT_BIT;
				PIN_RF_TX = 1;
			}
			break;

// ================== ONE =====================================	
		case TRANSMIT_ONE__START:
			if ( --Count == 0 )
			{
				PIN_RF_TX = 0;
				Count = ONE__LOW_LEVEL;
				State = END_OF_BIT_TRANSMIT;
			}
			break; 

// ================== ZERO ====================================	

		case TRANSMIT_ZERO__START:
			if ( --Count == 0 )
			{
				PIN_RF_TX = 0;
				Count = ZERO__LOW_LEVEL;
				State = END_OF_BIT_TRANSMIT;
			}
			break;	

// ================== END OF BIT ==============================	
		case END_OF_BIT_TRANSMIT:
			if ( --Count == 0 )
			{
				PIN_RF_TX = 1;
				State = NEXT_BIT;
				SelectBit <<= 1;

			}
			break;

		case SYNCHRO_BIT:
			if ( --Count == 0 )
			{
				State = RESET;
				RF_TX_START = FALSE;
				PIN_RF_TX = 0;
			}
			break;	

			default: 
				;
	}

}
